<?php


namespace app\controller\api;


use app\BaseController;
use app\models\order\OrderModel;
use app\models\order\RechargeOrderModel;
use app\models\user\UserModel;
use app\services\config\ConfigService;
use app\services\order\OrderService;
use app\services\user\DetailIntegralService;
use app\services\user\DetailMoneyService;
use app\strategy\pay\BalancePay;
use app\strategy\pay\WxPay;
use think\Exception;
use think\facade\Db;
use wxpay\WxpayService;

use app\services\pay\PayService;
use app\strategy\pay\AliPay;

class PayController extends BaseController
{
    /**
     * 支付
     * @return \think\response\Json
     */
    public function pay()
    {
        try {
            $orderSn = $this->request->param('order_sn');
            $orderSnAry = $this->request->param('orderSnAry');
            $userId = $this->request->userId;
            $user = UserModel::find($userId);

            if ($orderSnAry) {
                //多订单支付
                $order = OrderModel::where(['user_id' => $userId])->whereIn('order_sn', $orderSnAry)->select()->toArray();
                if (!$order || count($order) != count($orderSnAry)) {
                    throw new \Exception('订单有误');
                }

                foreach ($order as $key => $orderInfo) {
                    $user = UserModel::find($userId);

                    if ($orderInfo['order_status'] != 1) {
                        throw new \Exception('订单状态有误');
                    }

                    if ($orderInfo['pay_type'] == 1) {
                        throw new \Exception('当前支付方式未开通');
//                        $config = ConfigService::getConfigValueArray(['wechat_app_id', 'wechat_app_secret', 'mch_id', 'cert_no', 'mch_private_key', 'platform_cert', 'api_v3_secret']);
//                        $title = ConfigService::getConfigValue('site_title');
//                        $wxPay = new WxpayService($config['mch_id'] . '', $config['wechat_app_id'], $config['wechat_app_secret'], $config['api_v3_secret'], '', $config['cert_no']);
//                        $wxPay->setOrderName($title . '-订单支付');
//                        $wxPay->setOutTradeNo($orderSn);
//                        $wxPay->setTotalFee("0.01");
//                        $wxPay->setNotifyUrl(request()->domain() . '/api/Notify/wxPayNotify');
//                        $wxPay->setOpenid($user['open_id']);
//                        $result = $wxPay->doPay();
                    } elseif ($orderInfo['pay_type'] == 2) {
                        //支付宝支付
                        $amount = bcadd($amount, $orderInfo['pay_amount'], 2);

                    } elseif ($orderInfo['pay_type'] == 3) {
                        //支付余额验证
                        if ($user['money'] < $orderInfo['order_balance']) {
                            throw new \Exception('余额不足','20');
                        }
                        //消费积分验证
                        if ($user['integral'] < $orderInfo['order_integral']) {
                            throw new \Exception('消费积分不足','20');
                        }
                        $type = DetailMoneyService::ORDER_PAY;
                        DetailMoneyService::create($userId, $type, $orderInfo['order_balance'], $orderSn);

                        $type = DetailIntegralService::POINT_PAYMENT;
                        DetailIntegralService::create($userId, $type, $orderInfo['order_integral'], $orderSn);

                        $result = [];
                        OrderService::handleOrder($orderSn);
                    } else {
                        //余额支付
                        if ($user['money'] < $orderInfo['pay_amount']) {
                            throw new \Exception('余额不足','20');
                        }
                        $type = DetailMoneyService::ORDER_PAY;
                        DetailMoneyService::create($userId, $type, $orderInfo['pay_amount'], $orderSn);
                        $result = [];
                        OrderService::handleOrder($orderSn);
                    }
                }

                if ($orderInfo['pay_type'] == 2) {
                    //支付宝支付
                    $strategy = new AliPay();
                    $service = new PayService();
                    $service->setStrategy($strategy);
                    $notifyUrl = $this->request->domain() . '/api/Notify/aliPayNotify';
                    $amount = '0.01';
                    $orderStr = $service->pay('我是测试数据', 'App支付测试', $orderInfo['union_order_sn'], $amount, $notifyUrl);
                    return $this->success(['orderInfo' => $orderStr]);
                }
            } else {
                $orderInfo = OrderModel::where(['order_sn' => $orderSn, 'user_id' => $userId])->find();
                if (!$orderInfo) {
                    throw new \Exception('订单不存在');
                }
                if ($orderInfo['order_status'] != 1) {
                    throw new \Exception('订单状态有误');
                }
                if (!empty($address)) {
                    Db::name('order')->where('order_sn', $orderSn)->update([
                        'username' => $address['username'],
                        'user_mobile' => $address['user_mobile'],
                        'address_detail' => $address['full_address'],
                        'address_id' => $address['address_id']
                    ]);
                }

                if ($orderInfo['pay_type'] == 1) {
                    throw new \Exception('当前只开通了余额支付');
                    $config = ConfigService::getConfigValueArray(['wechat_app_id', 'wechat_app_secret', 'mch_id', 'cert_no', 'mch_private_key', 'platform_cert', 'api_v3_secret']);
                    $title = ConfigService::getConfigValue('site_title');
                    $wxPay = new WxpayService($config['mch_id'] . '', $config['wechat_app_id'], $config['wechat_app_secret'], $config['api_v3_secret'], '', $config['cert_no']);
                    $wxPay->setOrderName($title . '-订单支付');
                    $wxPay->setOutTradeNo($orderSn);
                    $wxPay->setTotalFee("0.01");
                    $wxPay->setNotifyUrl(request()->domain() . '/api/Notify/wxPayNotify');
                    $wxPay->setOpenid($user['open_id']);
                    $result = $wxPay->doPay();
                } elseif ($orderInfo['pay_type'] == 2) {
                    //支付宝支付
                    $strategy = new AliPay();
                    $service = new PayService();
                    $service->setStrategy($strategy);
                    $notifyUrl = $this->request->domain() . '/api/Notify/aliPayNotify';
                    //$orderStr = $service->pay('我是测试数据', 'App支付测试',$orderInfo['order_sn'],$orderInfo['pay_amount'], $notifyUrl);

                    $orderSn = createOrderSn();
                    OrderModel::where('id',$orderInfo['id'])->update(['union_order_sn' => $orderSn]);

                    $orderStr = $service->pay('我是测试数据', 'App支付测试', $orderSn, '0.01', $notifyUrl);
                    return $this->success(['orderInfo' => $orderStr]);
                } elseif ($orderInfo['pay_type'] == 3) {

                    //支付余额验证
                    if ($user['money'] < $orderInfo['order_balance']) {
                        throw new \Exception('余额不足','20');
                    }
                    //消费积分验证
                    if ($user['integral'] < $orderInfo['order_integral']) {
                        throw new \Exception('消费积分不足','20');
                    }


                    $type = DetailMoneyService::ORDER_PAY;
                    DetailMoneyService::create($userId, $type, $orderInfo['order_balance'], $orderSn);

                    $type = DetailIntegralService::POINT_PAYMENT;
                    DetailIntegralService::create($userId, $type, $orderInfo['order_integral'], $orderSn);

                    $result = [];
                    OrderService::handleOrder($orderSn);
                } else {
                    //余额支付
                    if ($user['money'] < $orderInfo['pay_amount']) {
                        throw new \Exception('余额不足','20');
                    }
                    $type = DetailMoneyService::ORDER_PAY;
                    DetailMoneyService::create($userId, $type, $orderInfo['pay_amount'], $orderSn);
                    $result = [];
                    OrderService::handleOrder($orderSn);
                }
            }
            return $this->success($result);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage(),$exception->getCode());
        }
    }

    /**
     * 订单支付详情
     * @return \think\response\Json
     */
    public function getPayInfo()
    {
        try {
            $orderSn = $this->request->param('order_sn');
            $orderInfo = OrderModel::where('order_sn', $orderSn)
                ->field('pay_time,order_sn,total_amount,pay_type,pay_amount,coupon_amount,traffic_fee,service_fee,is_pay')
                ->find();
            if (!$orderInfo) {
                throw new \Exception('订单不存在');
            }
            return $this->success($orderInfo);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 支付
     * @return \think\response\Json
     */
//    public function rechargePay()
//    {
//        try {
//            $orderSn = $this->request->param('order_sn');
//            $userId = $this->request->userId;
//            $user = UserModel::find($userId);
//            $orderInfo = Db::name('recharge_order')->where(['order_sn' => $orderSn, 'user_id' => $userId])->find();
//            if (!$orderInfo) {
//                throw new \Exception('订单不存在');
//            }
//            if ($orderInfo['is_pay'] == 1) {
//                throw new \Exception('订单已支付');
//            }
//            $title = ConfigService::getConfigValue('site_title');
//            $orderInfo['amount'];
//
//            $config = ConfigService::getConfigValueArray(['wechat_app_id', 'wechat_app_secret', 'mch_id', 'cert_no', 'mch_private_key', 'platform_cert', 'api_v3_secret']);
//            $title = ConfigService::getConfigValue('site_title');
//            $wxPay = new WxpayService($config['mch_id'] . '', $config['wechat_app_id'], $config['wechat_app_secret'], $config['api_v3_secret'], '', $config['cert_no']);
//            $wxPay->setOrderName($title . '-余额充值');
//            $wxPay->setOutTradeNo($orderSn);
//            $wxPay->setTotalFee("1");
//            $wxPay->setNotifyUrl(request()->domain() . '/api/Notify/wxRechargeNotify');
//            $wxPay->setOpenid($user['open_id']);
//            $result = $wxPay->doPay();
//            return $this->success($result);
//        } catch (\Exception $exception) {
//            return $this->error($exception->getMessage());
//        }
//    }

    /**
     * 余额充值 支付
     * @return \think\response\Json
     */
    public function rechargePay()
    {
        try {
            $orderSn = $this->request->param('order_sn');
            $pay_type = $this->request->param('pay_type');
            $userId = $this->request->userId;
            $orderInfo = RechargeOrderModel::where(['order_sn' => $orderSn, 'user_id' => $userId])->find();
            if (!$orderInfo) {
                throw new \Exception('订单不存在');
            }
            if ($orderInfo['is_pay'] == 1) {
                throw new \Exception('订单已支付');
            }
            $title = ConfigService::getConfigValue('site_title');

            if ($pay_type == 1) {

                throw new \Exception('当前未开通微信付款');

                //微信支付
                $service = new PayService();
                $service->setStrategy(new WxPay());
                $amount = $orderInfo['amount'];
                $userInfo = UserModel::find($orderInfo['user_id']);
                $openID = $userInfo['open_id'];
                $notifyUrl = $this->request->domain() . '/api/notify/wxRechargeNotify';
                $result = $service->pay($amount, $openID, $orderSn, $title, '余额充值', $notifyUrl, 0);

                RechargeOrderModel::where(['order_sn' => $orderSn, 'user_id' => $userId])->update(['pay_type' => 1]);
                return $this->success($result);

            } else if ($pay_type == 2) {

                //支付宝支付
                $strategy = new AliPay();
                $service = new PayService();
                $service->setStrategy($strategy);
                $notifyUrl = $this->request->domain() . '/api/Notify/aliPayRechargeNotify';
                $amount = $orderInfo['amount'];
                //$amount = '0.01';
                $title = ConfigService::getConfigValue('site_title');
                $orderStr = $service->pay($title . '-余额充值', 'App支付测试', $orderInfo['order_sn'], $amount, $notifyUrl);

                RechargeOrderModel::where(['order_sn' => $orderSn, 'user_id' => $userId])->update(['pay_type' => 1]);

                return $this->success(['orderInfo' => $orderStr]);
            } else {
                throw new \Exception('支付类型有误');
            }
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    public function cancelOrder()
    {
        try {
            $orderSn = $this->request->param('order_sn');
            $userId = $this->request->userId;
            $orderInfo = OrderModel::where(['order_sn' => $orderSn, 'user_id' => $userId])->find();
            if (!$orderInfo) {
                throw new \Exception('订单不存在');
            }
            if ($orderInfo['is_pay'] <= 1) {
                throw new \Exception('订单未支付');
            }
            if ($orderInfo['is_pay'] >= 7) {
                throw new \Exception('订单已完成');
            }
            if ($orderInfo['pay_type'] == 1) {
                $strategy = new BalancePay();
            } else {
                $strategy = new WxPay();
            }
            $service = new PayService();
            $service->setStrategy($strategy);
            $result = $service->refund($orderInfo['id']);
            return $this->success($result);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }
}